package com.mishow.activity.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.android.volley.Request;
import com.mishow.R;
import com.mishow.net.HttpUrlConstant;
import com.mishow.net.NetworkUtil;
import com.mishow.request.listener.OnResponseListener;
import com.mishow.request.response.ProfessionTypeResponse;
import com.mishow.request.response.UserInfoResponse;
import com.mishow.request.result.Profession;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.Constants;
import com.mishow.utils.ToastUtil;
import com.mishow.volley.http.request.FastJsonRequest;
import com.mishow.widget.AdjustLayout;

/**
 * 
 * 作者：wei.miao <br/>
 * 描述：标签选择器
 */
public class TagActivity extends BaseActivity {

	private Button btn_back;
	private TextView title_right;

	/** 平面拍摄AdjustLayout **/
	private AdjustLayout mAjustLayout;

	private ArrayList<String> mStrings;

	private String mTagType;

	/** 默认多选 **/
	private boolean mIsRadio;

	/** 职业类型显示标签 **/
	private ArrayList<String> mProfessionTypeTags = new ArrayList<String>();

	/**
	 * @param type
	 *            tag类型，可以类型为profession_type(职业类型)
	 * @param tags
	 *            已选择的标签列表
	 * @param title
	 *            页面标题
	 * @param requestCode
	 *            区分同一个页面请求不同的标签
	 * @param isRadio
	 *            单选传true
	 */
	public static void intoActivityForResult(Context ctx, String type,
			ArrayList<String> tags, String title, int requestCode,
			boolean isRadio) {
		Intent intent = new Intent(ctx, TagActivity.class);
		intent.putExtra(Constants.TAG_TYPE, type);
		intent.putExtra(Constants.TAG_TITLE, title);
		intent.putExtra(Constants.TAG_IS_RADIO, isRadio);
		if (tags != null && tags.size() > 0) {
			intent.putExtra(Constants.SELECTED_TAGS, tags);
		}
		((BaseActivity) ctx).startActivityForResult(intent, requestCode);
	}

	/**
	 * @param type
	 *            tag类型，可以类型为profession_type(职业类型)
	 * @param tags
	 *            已选择的标签列表
	 * @param title
	 *            页面标题
	 * @param requestCode
	 *            区分同一个页面请求不同的标签
	 */
	public static void intoActivityForResult(Context ctx, String type,
			ArrayList<String> tags, String title, int requestCode) {
		intoActivityForResult(ctx, type, tags, title, requestCode, false);
	}

	@Override
	protected void initData() {

		if (getIntent().getStringExtra(Constants.TAG_TYPE) != null) {
			mTagType = getIntent().getStringExtra(Constants.TAG_TYPE);
		} else {
			ToastUtil.show(mContext, "数据错误");
			finish();
		}
		if (getIntent().getStringExtra(Constants.TAG_TITLE) != null) {
			setTitle(getIntent().getStringExtra(Constants.TAG_TITLE));
		}

		mIsRadio = getIntent().getBooleanExtra(Constants.TAG_IS_RADIO, false);

		if (getIntent().getParcelableArrayListExtra(Constants.SELECTED_TAGS) != null) {
			mStrings = getIntent().getStringArrayListExtra(Constants.SELECTED_TAGS);
		} else {
			mStrings = new ArrayList<>();
		}

	}

	@Override
	protected void initView(Bundle savedInstanceState) {

		setContentView(R.layout.activity_profession_type);

		btn_back = (Button) findViewById(R.id.btn_back);
		title_right = (TextView) findViewById(R.id.title_right);

		mAjustLayout = (AdjustLayout) findViewById(R.id.adjust_plane_layout);
	}

	@Override
	protected void setAttribute() {

		btn_back.setOnClickListener(onClickListener);
		title_right.setOnClickListener(onClickListener);
		title_right.setVisibility(View.VISIBLE);
		title_right.setText("保存");
		title_right.setTextColor(mContext.getResources().getColor(
				R.color.search_pop_color));

		// 服务端获取标签
		getTagsFromApi();
		// 选择标签的数量
		refreshSelectedCount();
	}

	/**
	 * 服务端获取标签
	 */
	private void getTagsFromApi() {

		if (!AndroidUtil.isNetworkAvailable(this)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		// params.put("tag_type", mTagType);

		Map<String, String> lastParams = NetworkUtil
				.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(this,HttpUrlConstant.GET_PERFESSION_TYPE);
		OnResponseListener<ProfessionTypeResponse> listener = new OnResponseListener<ProfessionTypeResponse>(this) {

			@Override
			public void onSuccess(ProfessionTypeResponse response) {

				ArrayList<Profession> professions = response.getBody()
						.getResult();
				for (int i = 0; i < professions.size(); i++) {

					mProfessionTypeTags.add(professions.get(i).getProfessionName());
				}

				setUpAllTags(mProfessionTypeTags);
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
			}

			@Override
			public void onCompleted() {

				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<ProfessionTypeResponse>(
				Request.Method.POST, postUrl, ProfessionTypeResponse.class,
				listener, listener).setParams(lastParams));

	}

	/**
	 * 获取标签数据成功
	 * 
	 * @param tags
	 */
	private void setUpAllTags(ArrayList<String> tags) {

		/*ArrayList<String> delList = new ArrayList();//用来装需要删除的元素
		
        for (String string :mStrings) {
            if (!tags.contains(string)) {

                delList.add(string);
                
            }
        }
        mStrings.remove(delList);*/
		
		Iterator ite = mStrings.iterator();
		while(ite.hasNext()){
			
		String string  = (String)ite.next();
		if(!tags.contains(string))
			
			ite.remove();
		}
        
		for (final String s : tags) {
			final CheckBox checkbox = (CheckBox) LayoutInflater.from(mContext)
					.inflate(R.layout.view_tag_checkbox, null);
			checkbox.setText(s);
			checkbox.setChecked(mStrings.contains(s));
			checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton compoundButton,boolean b) {
					if (mIsRadio) {
						for (int j = 0; j < mAjustLayout.getChildCount(); j++) {
							mStrings = new ArrayList<String>();
							((CheckBox) mAjustLayout.getChildAt(j))
									.setChecked(false);
						}
					}
					if (b) {
						mStrings.add(s);
					} else {
						mStrings.remove(s);
					}
					checkbox.setChecked(b);

					refreshSelectedCount();
				}
			});
			mAjustLayout.addView(checkbox);
			refreshSelectedCount();
		}

	}

	/**
	 * refresh标题栏显示的选择数
	 */
	private void refreshSelectedCount() {
		int total = mStrings.size();
		// mTitleRight.setText("已选 (" + total + ")");
	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_back:
				finish();
				break;
			case R.id.title_right:// 保存
				Intent intent = new Intent();
				intent.putExtra(Constants.SELECTED_TAGS, mStrings);
				setResult(RESULT_OK, intent);
				finish();
				break;
			default:
				break;
			}
		}
	};

}
